#include "welimp.h"

struct bigstr* wel_init(struct bigstr *bstr) {

	if(bstr == NULL) return NULL;
	bstr->bytes = LINE_LEN;
	bstr->mstxt = (char *)malloc(bstr->bytes * sizeof(char));
	return bstr;

}
/**
 *核心函数：负责从文件中读取内容到自定义结构体
 */
struct bigstr* wel_load(struct bigstr *bstr) {
	int size = 0;
	char *buf;
	char line[LINE_LEN];
	FILE *in;
	if(bstr == NULL) return NULL;
	if((in = fopen("welcom.txt", "r")) == NULL)  {
		printf("文件打开异常！");
		exit(1);
	}
	/*增长策略：每次读取一行加入末尾，如果原始空间不足，则以LINE_LEN(100)增长*/
	while(fgets(line, LINE_LEN, in) != NULL) {
		size += strlen(line);
		if(size+1 > bstr->bytes) {                /*注意'\0'*/
			bstr->bytes += LINE_LEN;
			buf = bstr->mstxt;
			bstr->mstxt = (char *)malloc(bstr->bytes);
			memcpy(bstr->mstxt, buf, strlen(buf));
			free(buf);		          /*回收旧内存*/
		}
		strcat(bstr->mstxt, line);
	}
	if(fclose(in) != 0) {
		printf("文件关闭异常！");
	}
	return bstr;
}

void wel_show(struct bigstr *bstr) {
	puts(bstr->mstxt);
}

void wel_finalize(struct bigstr *bstr) {
	free(bstr->mstxt);
}
